import { getCartList, changeCount, delCart } from '@/api/cart'
import { Toast } from 'vant'

// 购物车列表存到vuex
export default {
  namespaced: true,
  state () {
    return {
      cartList: []
    }
  },
  // 同步,用this.$store.commint('cart/xxx', xx)调用
  mutations: {
    // 设置cartList
    setCartList (state, newList) {
      state.cartList = newList
    },
    toggleCheck (state, goodsId) {
      const goods = state.cartList.find(e => e.goods_id === goodsId)
      goods.isChecked = !goods.isChecked
    },
    toggleAllCheck (state, flag) {
      state.cartList.forEach(e => {
        e.isChecked = flag
      })
    },
    changCount (state, { goodsNum, goodsId }) {
      const goods = state.cartList.find(e => e.goods_id === goodsId)
      goods.goods_num = goodsNum
    }
  },
  // 异步,发请求写在这里,用this.$store.dispatch('cart/xxx')调用
  actions: {
    async getCartListAction (store) {
      const { data: { list } } = await getCartList()

      // 后台返回的数据不包含复选框选中状态
      list.forEach(e => {
        e.isChecked = true
      })

      store.commit('setCartList', list)
    },
    async changCount (store, { goodsNum, goodsId, goodsSkuId }) {
      // 先更新本地数量 => 更新页面显示
      store.commit('changCount', { goodsNum, goodsId })
      // 再更新后台
      await changeCount(goodsId, goodsNum, goodsSkuId)
    },
    async delSelect (store) {
      const selCartList = store.getters.selCartList
      const cartIds = selCartList.map(e => e.id)
      await delCart(cartIds)
      Toast('删除成功')
      store.dispatch('getCartListAction')
    }
  },
  // 基于state衍生的属性,第一个参数是state
  getters: {
    // 购物车商品总数
    cartTotal (state) {
      return state.cartList.reduce((sum, item) => sum + item.goods_num, 0)
    },
    // 选中的商品
    selCartList (state) {
      return state.cartList.filter(e => e.isChecked)
    },
    // 选中的商品总数
    selCount (state, getters) {
      return getters.selCartList.reduce((sum, item) => sum + item.goods_num, 0)
    },
    // 选中的商品总价
    selPrice (state, getters) {
      return getters.selCartList.reduce((sum, item) => sum + item.goods_num * item.goods.goods_price_min, 0).toFixed(2)
    },
    // 是否全选
    isAllCheck (state) {
      return state.cartList.every(e => e.isChecked)
    }
  }
}
